package lc.q51_100;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 二叉搜索树原型
 */
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    TreeNode(int x) { val = x; }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public List<Integer> iterable() {
        // 按层数遍历
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> s = new Stack<>();
        s.add(this);
        while (!s.empty()) {
            Stack<TreeNode> nextStock = new Stack<>();
            while (!s.empty()) {
                TreeNode pop = s.pop();
                if (pop == null) {
                    list.add(null);
                } else {
                    list.add(pop.val);
                    nextStock.push(pop.right);
                    nextStock.push(pop.left);
                }

            }
            s = nextStock;
        }
        // 末尾的null去掉
        for (int i = list.size() - 1;i >= 0 ; i--) {
            if (list.get(i) == null) {
                list.remove(i);
            } else {
                break;
            }
        }
        return list;
    }

}
